<?php
/**
 * Created by PhpStorm.
 * User: W
 * Date: 2018/2/24
 * Time: 10:36
 */

namespace app\console\controller;

use app\common\controller\Console;
use think\Loader;
use think\Log;

class Goods extends Console {

    public function index()
    {
        $where  = [];
        $q = request()->get('q');
        $post_status = request()->get('post_status');
        if ($q)
            $where['post_title|post_format'] = ['like',"%$q%"];
        if (isset($post_status))
            $where['status']=$post_status;
        $model = model('Goods');
        $result = $model->order('id desc')->where($where)->paginate(10, false, ['query'=>request()->param()])->each(function($item, $key){
            $img_arr = unserialize($item['head_img']);
            $item['head_img'] = $img_arr[0];
            return $item;
        });
        $this->assign([
            'result' => $result,
        ]);
        return $this->fetch();
    }

    public function add() 
    {
        $cate_model = model('Cates');
        $cates = $cate_model->select();
        $this->assign('cates', $cates);
        return $this->fetch();
    }

    public function insert() {
        if ($data = request()->post()) {
            $validate = Loader::validate('Goods');
            if(!$validate->check($data)){
                return json(['status' => 'fail', 'info' => $validate->getError()]);
            }
            $data['create_at'] = time();
            $data['update_at'] = time();
            if ($data['head_img']) {
                $data['head_img']  =   serialize($data['head_img']);
            }
            if (isset($data['editorValue'])) {
                unset($data['editorValue']);
            }
            $model = model('Goods');
            try{
                $model->data($data)->save();
                return $this->success('添加成功',url('index'));
            } catch (Exception $e) {
                Log::record($e->getMessage());
                return $this->success('添加失败');
            }
            
        }
    }

    public function edit($id)
    {
        $model = model('Goods');
        $info = $model->where('id', $id)->find();
        $cate_model = model('Cates');
        $cates = $cate_model->select();
        $this->assign([
            'info'  =>  $info,
            'cates' =>  $cates
        ]);
        return $this->fetch();
    }

    public function update() 
    {
        if ($data = request()->post()) {
            $validate = Loader::validate('Goods');
            if(!$validate->check($data)){
                return json(['status' => 'fail', 'info' => $validate->getError()]);
            }
            if ($data['head_img']) {
                $data['head_img']  =   serialize($data['head_img']);
            }
            if (isset($data['editorValue'])) {
                unset($data['editorValue']);
            }
            $id = $data['id'];
            unset($data['id']);
            $data['update_at'] = time();
            //var_dump($data);die;
            $model = model('Goods');
            try{
                $model->lock(true)->where('id', $id)->find();
                $model->save($data, ['id' => $id]);
                return json(['status' => 'success', 'info' => '更新成功']);
            } catch (Exception $e) {
                Log::record($e->getMessage());
                return json(['status' => 'success', 'info' => '更新失败']);
            }

        }
    }

    public function change($id, $type)
    {
        if ($type == 'pass') {
            $data = [
                'post_modified' => time(),
                'post_status'   => 1
            ];
        } elseif ($type == 'del') {
            $data = [
                'post_modified' => time(),
                'is_del'   => 2
            ];
        } else {
            $this->error('操作方式错误');
        }
        $model = model('Posts');
        $model->lock(true)->where('post_id', $id)->find();
        $model->save($data, ['post_id' => $id]);
        return redirect($_SERVER['HTTP_REFERER']);
    }

    public function format($id)
    {
        $q = request()->get('q');
        if ($q)
            $where['name|price'] = ['like',"%$q%"];
        $where['goods_id'] = $id;
        $model = model('Sku');
        $list = $model->where($where)->paginate(10, false, ['query'=>request()->param()])->each(function ($item, $key){
            $res = model('SkuItem')
                ->field('items.name')
                ->join('items', 'sku_item.item_id=items.id', 'left')
                ->where('sku_item.sku_id', $item['id'])->select();
            $info = [$item['name']];
            foreach ($res as $v) {
                $info[] = $v['name'];
            }
            $item['name'] = implode('+', $info);
        });
        $this->assign([
            'goods_id' => $id,
            'list'  => $list
        ]);
        return $this->fetch();
    }

    public function format_add($goods_id)
    {
        $list = model('ItemCates')->select();
        $item_model = model('Items');
        foreach ($list as &$v) {
            $v['items'] = $item_model->where('item_cate_id', $v['id'])->select();
        }
        $this->assign([
            'list' => $list,
            'goods_id' => $goods_id,
        ]);
        return $this->fetch();
    }

    public function format_insert()
    {
        $data = request()->post();
        $sku_data = [
            'goods_id' => $data['goods_id'],
            'name' => $data['name'],
            'price' => $data['price'],
            'number' => $data['number'],
            'create_at' => time(),
            'update_at' => time(),
        ];
        $sku_id = model('Sku')->insertGetId($sku_data);
        unset($data['goods_id']);unset($data['price']);unset($data['name']);unset($data['number']);
        $items_data = [];
        foreach ($data as $k => $v) {
            if ($v) {
                $items_data[] = [
                    'sku_id' => $sku_id,
                    'item_id' => $v,
                    'item_cates_id' => $k,
                    'number' => $sku_data['number'],
                    'create_at' => time(),
                    'update_at' => time(),
                ];
            }
        }
        model('SkuItem')->insertAll($items_data);
        model('Goods')->where('id', $sku_data['goods_id'])->setInc('number', $sku_data['number']);
        $this->success('添加成功');
    }

    public function format_number_add($id)
    {
        $info = model('Sku')->where('id', $id)->find();
        $this->assign([
            'info' => $info,
        ]);
        return $this->fetch();
    }

    public function format_number_insert()
    {
        $data = request()->post();
        model('Sku')->where('id', $data['id'])->setInc('number', $data['number']);
        $this->success('操作成功');
    }

    public function format_detail($id)
    {
        $list = model('SkuItem')
            ->field('sku_item.*, items.name')
            ->join('items', 'sku_item.item_id=items.id','left')
            ->where('sku_id', $id)
            ->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function del($id)
    {
        model('Goods')->where('id', $id)->delete();
        return $this->redirect($_SERVER['HTTP_REFERER']);
    }

    public function format_del($id)
    {
        $info = model('Sku')->where('id', $id)->find();
        model('Goods')->where('id', $info['goods_id'])->setDec('number', $info['number']);
        model('Sku')->where('id', $id)->delete();
        return $this->redirect($_SERVER['HTTP_REFERER']);
    }
}